package com.chd.driversystem.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.chd.driversystem.domain.User;
import com.chd.driversystem.gen.BeanServer;
import com.chd.driversystem.util.tools.Constants;
import com.chd.driversystem.util.tools.LogUtil;
import com.chd.driversystem.util.tools.MyApplication;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class DriverSystemService extends Service {

    private static final String TAG = "DriverSystemService";
    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static final int LOGINACTIVITY = 0;
    public static final int DRIVERACTIVITY = 1;
    public static final int EVALUATIONACTIVITY = 2;
    public static final int MANAGERACTIVITY = 3;
    public static final int RANKINGACTIVITY = 4;

    private int whereis = -1;
    private Map<String, Object> params;
    private boolean isBusy = false;


    private SystemBindler mBindler = new SystemBindler();

    public DriverSystemService() {
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d(TAG, "onStartCommand-whereis=" + whereis);
        sendNetRequest();

        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long threeSencond = SystemClock.elapsedRealtime() + 30 * 60 * 1000;
        Intent intent1 = new Intent(this, DriverSystemService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, intent1, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, threeSencond, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBindler;
    }

    public class SystemBindler extends Binder {
        public void setWhere(int where) {
            whereis = where;
        }

        public void setParams(Map<String, Object> map) {
            while (!permission(false)) ;
            params = map;
            permission(true);
        }

        public void refreshNetData() {
            sendNetRequest();
        }
    }

    /**
     * 管理params的访问权限
     *
     * @param isGet 表示是否已经拥有权限，有则释放权限，否则代表申请权限
     * @return
     */
    public synchronized boolean permission(boolean isGet) {
        boolean rst = false; //标识操作是否成功
        if (isGet) {
            isBusy = false;
            rst = true;
        } else if (!isBusy) {
            isBusy = true;
            rst = true;
        }
        return rst;
    }

    public void sendNetRequest() {
        Log.d(TAG, "sendNetRequest() whereis=" + whereis);
        switch (whereis) {
            case LOGINACTIVITY:
                break;
            case DRIVERACTIVITY:
                while (!permission(false)) ;
                try {
                    if (params != null && !params.isEmpty()) {
                        User user = MyApplication.getUser();
                        HttpService.startServiceEvaluation(MyApplication.getContext(),
                                user.getId(),
                                (Integer) params.get(Constants.EXTRA_PARAM1));
                        HttpService.startServiceDrivingRecord(
                                MyApplication.getContext(),
                                user.getCode(),
                                dateFormat.parse("2014-04-01"),
                                dateFormat.parse("2017-11-01"),
                                0
                        );
                        HttpService.startServiceDrivingRecord(
                                MyApplication.getContext(),
                                user.getCode(),
                                dateFormat.parse("2014-04-01"),
                                dateFormat.parse("2017-11-01"),
                                1
                        );
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                permission(true);
                break;
            case EVALUATIONACTIVITY:
                while (!permission(false)) ;
                if (params != null && !params.isEmpty()) {
                    HttpService.startServiceEvaluation(MyApplication.getContext(),
                            (Long) params.get(Constants.EXTRA_PARAM1),
                            (Integer) params.get(Constants.EXTRA_PARAM2));
                }
                permission(true);
                break;
            case MANAGERACTIVITY:
                while (!permission(false)) ;
                if (params != null && !params.isEmpty()) {
                    Long managerId = MyApplication.getUser().getId();
                    HttpService.startServiceEvaluation(MyApplication.getContext(),
                            managerId,
                            (Integer) params.get(Constants.EXTRA_PARAM1));
//                    List<User> users = BeanServer.getInstance().getUserListByManangerId(managerId);
//                    try {
//                        for (User user:users) {
//                            HttpService.startServiceDrivingRecord(
//                                    MyApplication.getContext(),
//                                    user.getCode(),
//                                    dateFormat.parse("2014-04-01"),
//                                    dateFormat.parse("2017-11-01"),
//                                    0
//                            );
//                            HttpService.startServiceDrivingRecord(
//                                    MyApplication.getContext(),
//                                    user.getCode(),
//                                    dateFormat.parse("2014-04-01"),
//                                    dateFormat.parse("2017-11-01"),
//                                    1
//                            );
//                        }
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }
                }
                permission(true);
                break;
            case RANKINGACTIVITY:
                LogUtil.d(TAG, "httpserver called params = " + params);
                while (!permission(false)) ;
                if (params != null && !params.isEmpty()) {
                    List<User> users = BeanServer.getInstance().getDriverUsers();

                    HttpService.startServiceEvaluationByUserList(MyApplication.getContext(),
                            (ArrayList<User>) users,
                            (Integer) params.get(Constants.EXTRA_PARAM1));
                }
                permission(true);
                break;
            default:
                break;
        }
    }
}
